package com.tobias.gaokao.service.impl;

import com.tobias.gaokao.dao.StudentRepository;
import com.tobias.gaokao.model.Student;
import com.tobias.gaokao.service.StudentService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import com.tobias.gaokao.constants.PTConstants;
import com.tobias.gaokao.constants.Result;
import com.tobias.gaokao.constants.ResultEnum;
import com.tobias.gaokao.constants.ResultUtil;

import javax.servlet.http.HttpSession;

/**
 * 
 * @author TobiasWang 2022/06/16
 */
@Service(value = "userService")
public class UserServiceImpl implements StudentService {
	private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	private final static String TOKEN = "token";

	@Autowired
	private StudentRepository studentRepository;

	@Override
	public Result login(String rawData, HttpSession session) {

		String userName = (String) JSONObject.fromObject(rawData).get("username");
		String password = (String) JSONObject.fromObject(rawData).get("password");

		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
			return ResultUtil.error(ResultEnum.INPUT_EMPTY);
		}

		Student student = studentRepository.findBySocialId(password);

		if (ObjectUtils.isEmpty(student)) {
			logger.error("->The user is not find in the database: {}", student);
			return ResultUtil.error(ResultEnum.USER_NOT_FOUND);
		}
		if (!userName.equals(student.getName())) {
			logger.info("->password error: {}", student);
			return ResultUtil.error(ResultEnum.WRONG_PASS);
		}
		if (null != session.getAttribute("userName")) {
			logger.error("->The user can not login twice error, {} is still on line", session.getAttribute("userName"));
			return ResultUtil.error(ResultEnum.REPEAT_LOGIN);
		}
		session.setAttribute(PTConstants.USER_NAME, userName);
		session.setAttribute(PTConstants.STUDENT_SCHOOL, student.getSchool());
		session.setAttribute(PTConstants.UNIQUE_NUMBER, student.getUniqueNumber());
		session.setAttribute(PTConstants.STUDENT_TYPE, student.getStudentType());
		session.setMaxInactiveInterval((int) (PTConstants.EXPIRE_TIME));
		logger.info("->User successful login to the system: {}", student);
		String gender = student.getGender()==0 ? "女" : "男";
		String type = student.getStudentType()==0 ? "文史类" : "理工类";
		return ResultUtil.success(userName + "  " + gender + "  " + student.getSchool()+ "  " + type);
	}

}
